package org.mspring.mlog.web.module.web.widget;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.service.PostService;
import org.mspring.platform.utils.DateUtils;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Gao Youbo
 * @since 2013年9月23日
 */
@Widget
@RequestMapping("/widget/post")
public class Widget_PostWidget extends Widget_AbstractWidget {

    @Autowired
    private PostService postService;

    /**
     * 最新文章
     *
     * @param tpl
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/recent")
    public String recent(@RequestParam(required = false, defaultValue = "/widget/post/recent") String tpl, HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer num = RequestUtils.getRequestParameterAsInteger(request, "num");
        if (num == null) {
            num = 10;
        }
        List<Post> posts = postService.recent(num);
        model.addAttribute("posts", posts);
        return "skin:" + tpl;
    }

    /**
     * 热门文章，点击率最高
     *
     * @param tpl
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/hot")
    public String hot(@RequestParam(required = false, defaultValue = "/widget/post/hot") String tpl, HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer num = RequestUtils.getRequestParameterAsInteger(request, "num");
        if (num == null) {
            num = 10;
        }
        Date start = RequestUtils.getRequestParameterAsDate(request, "start");
        Date end = RequestUtils.getRequestParameterAsDate(request, "end");
        if (start == null) {
            start = DateUtils.addMonths(new Date(), -1);
        }
        if (end == null) {
            end = new Date();
        }
        List<Post> posts = postService.hot(num, start, end);
        model.addAttribute("posts", posts);
        return "skin:" + tpl;
    }
}
